<template>
    <div class="text_container">
        <ZWGroup ref="ZWGroupRef" :group-id="groupId" :type="1" @submit="getGroup" />
        <div class="text_main">
            <ZwSearchForm row-num="3" :option="searchOption" @search="search" @reset="reset" />
            <ZwTable
                ref="tableRef"
                class="table-box"
                tab-h="initial"
                :option="tableOption"
                :row-key="getRowKey"
                :fetch-params="state.searchParams"
                :fetch-api="fetchApi()"
                :close-loading="true"
                @selection-change="sectionChange"
                @select-all="selectAll">
                <template #headerOperate>
                    <FormulaBar
                        ref="FormulaBarRef"
                        :type="1"
                        @batchTag="batchTag"
                        @batchDel="batchDel"
                        @exprotWordArt="exprotWordArt"
                        @newWordArt="newWordArt"></FormulaBar>
                </template>
            </ZwTable>
        </div>
        <div class="right_container">
            <div class="right_container_top">
                <!-- <Search ref="SearchRef" @submit="searchList" :isBoth="isBoth" :type="1" @getTableH="getTableH"></Search> -->
                <!-- <FormulaBar ref="FormulaBarRef" :type="1" @batchTag="batchTag" @batchDel="batchDel" @exprotWordArt="exprotWordArt" @newWordArt="newWordArt"></FormulaBar> -->
            </div>
            <!-- 表格 -->
            <!-- <ZWTable ref="tableRef" :tableParams="tableParams" :tableData="tableData" /> -->
            <!-- 分页 -->
            <!-- <ZWPagination ref="PaginationRef" @submit="getPage" /> -->
        </div>
        <!-- 标签弹框 -->
        <ZWSelectTag ref="SelectTagRef" @submit="getTags" />
        <!-- 删除弹框 -->
        <ZWDeletdialog ref="DeletdialogRef" page-type="text" @submit="del" />
        <!-- 上传弹框 -->
        <Upload ref="UploadRef" @submit="initList" />
        <!--导入/新建话术  -->
        <WordArt
            ref="WordArtRef"
            :type="1"
            :group-id="groupId === 'all' ? 0 : groupId"
            @submit="refreshGroup"
            @groupIdChange="groupIdChange" />
    </div>
</template>

<script setup lang="tsx">
import ZWGroup from '@/components/ZWGroup.vue';
import Search from '../../components/Search.vue';
import FormulaBar from '../../components/FormulaBar.vue';
import Upload from '../../components/Upload.vue';
import ZWTable from '@/components/ZWTable.vue';
import ZWSelectTag from '@/components/ZWSelectTag.vue';
import ZWDeletdialog from '@/components/ZWDeletdialog.vue';
import ZWPagination from '@/components/ZWPagination.vue';
import WordArt from '@/components/WordArt.vue';
import { ref, reactive, onMounted, computed, watch, onBeforeMount } from 'vue';
import { batchTagAdd, batchTagDel, editTextTag } from '@/api/common';
import { textInfo, getTextList, batchContentDel, batchContentDel1 } from '@/api/concreation';
import { getSetionId } from '@/utils/utils';
import ZwSearchForm from '@/components/zw/search-form/SearchForm';
import ZwTable from '@/components/zw/table/Table';
import { useStore } from '@/store';
import { ElButton, ElMessage } from 'element-plus';
import { getCreateList } from '@/api/common';
import { deepCopy } from '@/utils/helper';
import { endLoading, startLoading } from '@/utils/request';

const store = useStore();
const DeletdialogRef = ref(null);
const WordArtRef = ref(null);
const groupId = ref<number | string>('all');
const SelectTagRef = ref(null);
const PaginationRef = ref(null);
const isBoth = ref(true);
const ZWGroupRef = ref(null);
const tableRef = ref(null);
let pageInfo = reactive({});
// 选中复选框
const table = computed(() => {
    return store.getters['table'];
});
const defaultParams = reactive({
    title: '',
    user_id: [],
    create_time: [],
    tag_list: [],
    group_id: groupId.value || 0
});
const state = reactive({
    searchParams: deepCopy(defaultParams)
});
const getRowKey = (row: any) => {
    return row.id;
};
const searchOption = computed(() => {
    return [
        {
            label: '文本搜索',
            name: 'title',
            value: '',
            type: 'input',
            width: '280px',
            placeholder: '请输入标题/内容进行查找'
        },
        {
            label: '创建人',
            name: 'user_id',
            value: [],
            multiple: true,
            type: 'select',
            filterable: true,
            placeholder: '请选择创建人',
            fetchOptionApi: () => {
                return new Promise(resolve => {
                    getCreateList({}).then((res: any) => {
                        const targetArr = res.map((item: any) => {
                            item.name = `${item.name}  (${item.phone}) `;
                            return item;
                        });
                        resolve(targetArr);
                    });
                });
            },
            formatOption: (v: any) => ({
                label: v.name,
                value: v.id
            })
        },
        {
            label: '添加时间',
            name: 'create_time',
            value: [],
            type: 'datePicker',
            datePickerType: 'daterange',
            datePickerFormat: 'YYYY-MM-DD HH:mm:ss',
            valueFormat: 'YYYY-MM-DD HH:mm:ss',
            startPlaceholder: '开始时间',
            endPlaceholder: '结束时间'
        },
        {
            label: '标签筛选',
            name: 'tag_list',
            value: [],
            type: 'select',
            popperClass: 'zw-hide_select_option',
            placeholder: '请选择标签',
            multiple: true,
            isTagSelect: true,
            formatOption: v => ({
                label: v.name,
                value: v.id
            })
        }
    ];
});
const tableOption = [
    {
        type: 'selection',
        width: 55,
        fixed: 'left',
        reserveSelection: true
    },
    {
        prop: 'title',
        label: '标题',
        width: 200
    },
    {
        prop: 'content',
        label: '内容',
        width: 200,
        showOverflowTooltip: true
    },
    {
        prop: 'tags',
        label: '标签',
        width: 400,
        isTag: true
    },
    {
        label: '创建人',
        render({ row, column, index }) {
            return <span>{row.user_name || '--'}</span>;
        }
    },
    {
        label: '添加时间',
        width: 200,
        render({ row, column, index }) {
            return <span>{row.created_at || '--'}</span>;
        }
    },
    {
        prop: 'operate',
        label: '操作',
        fixed: 'right',
        width: 280,
        isOperate: true,
        renderOperate({ row, column, index }) {
            return (
                <div class="handle">
                    <ElButton size="small" onClick={() => Edit(row)}>
                        编辑
                    </ElButton>
                    <ElButton size="small" onClick={() => changeTag(row)}>
                        修改标签
                    </ElButton>
                    <ElButton size="small" onClick={() => remove(row)}>
                        删除
                    </ElButton>
                </div>
            );
        }
    }
];
const fetchApi = () => {
    // 获取文件列表
    // getTableH()
    return getTextList;
};
const sectionChange = (selection: any) => {
    store.dispatch('table', {
        tableData: selection
    });
};
const selectAll = (selection: any) => {
    store.dispatch('table', {
        tableData: selection,
        tableAll: true
    });
};
const search = (data: any) => {
    tableRef.value?.clearSelection();
    const res = { ...defaultParams, ...data };
    state.searchParams = { ...deepCopy(res), group_id: groupId.value };
};
const reset = (v?: any) => {
    tableRef.value?.clearSelection();
    state.searchParams = deepCopy({ ...v, group_id: store.getters.group_id });
};
const pageList = reactive({
    page: 1,
    page_size: 15
});
// 选择IDList
const sectionIds = ref([]);
// 选中的id
const selfSelectId = ref(0);
const ZWgroupId = ref(0);
//获取表格高度
const getTableH = () => {
    tableRef.value.getTableH();
};
// 修改标签确认
const getTags = (data: any) => {
    startLoading();
    try {
        editTextTag({
            content_id: sectionIds.value[0],
            tag_ids: getSetionId('id', data) //选中标签ID
        }).then((res: any) => {
            ElMessage.success('修改标签成功');
            startLoading();
            tableRef.value?.clearSelection();
            tableRef.value.reload();
            // initList();
        });
    } catch (error) {}
};
//是否批量
const IsBatch = ref(true);
// 编辑h话术弹框
const Edit = (val: any) => {
    WordArtRef.value.isEdit = true;
    WordArtRef.value.appDialog.title = '编辑话术';
    WordArtRef.value.wordVisible = true;
    store.dispatch('content/openWordArt', true);
    store.dispatch('content/isNewWord', true);
    textInfo({
        media_content_id: val.id,
        noNeedLoading: false
    })
        .then((res: any) => {
            WordArtRef.value.editInfo = res;
        })
        .catch(() => {});
};
// 修改标签
const changeTag = (val: any) => {
    sectionIds.value = [val.id];
    SelectTagRef.value.selectTags = val.tags;
    SelectTagRef.value.appDialog.title = '修改标签';
    SelectTagRef.value.appDialog.visible = true;
};
// 删除
const remove = (val: any) => {
    selfSelectId.value = val.id;
    IsBatch.value = false;
    DeletdialogRef.value.appDialog.visible = true;
};
// 批量删除
const batchDel = () => {
    IsBatch.value = true;
    DeletdialogRef.value.appDialog.visible = true;
};
const exprotWordArt = () => {
    WordArtRef.value.wordVisible = true;
    WordArtRef.value.appDialog.title = '导入文本';
};
const newWordArt = () => {
    WordArtRef.value.appDialog.title = '新建文本';
    WordArtRef.value.wordVisible = true;
};
// 删除确认
const del = async () => {
    startLoading();
    try {
        //  删除
        await batchContentDel({
            type: 1,
            content_ids: IsBatch.value ? sectionIds.value : [selfSelectId.value]
        });
        ElMessage.success(`${IsBatch.value ? '批量' : ''}删除成功`);
        DeletdialogRef.value.appDialog.visible = false;
        store.dispatch('table', {
            tableData: [],
            tableAll: false
        });
        // refreshGroup()
        tableRef.value?.clearSelection();
        ZWGroupRef.value.getGroup();
        tableRef.value.reload();

        // getText(pageInfo)

        ZWgroupId.value = groupId.value;
    } catch (e) {
        endLoading();
    }
};
// 批量确认
const batchTag = async (data: any) => {
    const params = {
        type: 1,
        content_ids: sectionIds.value,
        tag_ids: getSetionId('id', data.tag_ids) //选中标签ID
    };
    //0 批量打 1批量删除      //批量打标签              // 批量删除
    try {
        data.defaultVal == 0 ? await batchTagAdd(params) : await batchTagDel(params);
        ElMessage.success(`批量${data.defaultVal ? '移除' : '打'}标签成功`);
        // refreshGroup()
        tableRef.value?.clearSelection();
        tableRef.value.reload();
        getText(pageInfo);
    } catch (e) {}
};

const tableData = ref([]);
// const tableParams = reactive({
//   selection: true,
//   tabH: [
//     { label: '标题', prop: 'title', width: 200, align: 'left', fixed: 'left' },
//     { label: '内容', prop: 'content', width: 200, align: 'left', showTip: true },
//     { label: '标签', prop: 'tags', width: 400, isTag: true, align: 'left' },
//     { label: '创建人', prop: 'user_name', width: 200, align: 'left' },
//     { label: '添加时间', prop: 'created_at', width: 200, align: 'left' },
//     {
//       label: '操作',
//       action: true,
//       width: 240,
//       align: 'left',
//       fixed: 'right',
//       fn: [
//         { id: 0, name: '编辑', click: Edit },
//         { id: 1, name: '修改标签', click: changeTag },
//         { id: 2, name: '删除', click: remove }
//       ]
//     }
//   ]
// })
const getGroup = (data: any) => {
    groupId.value = data?.id;
    state.searchParams = { ...deepCopy(state.searchParams), group_id: data.id };
    tableRef.value?.clearSelection();
};
const getPage = (data: any) => {
    pageList.page = data.page;
    pageList.page_size = data.page_size;
    getText();
};
// 获取文件列表
const getText = (data?: any) => {
    pageInfo = data;
    const params = {
        group_id: groupId.value,
        title: data?.keyword || '',
        page: pageList.page,
        page_size: pageList.page_size,
        ...data
    };
    delete params.page_size;
    getTextList(params).then((res: any) => {
        tableData.value = res.data;
        store.dispatch('pageTotal', res.total);
    });
};
const initList = (val?: any) => {
    const params = { ...val, id: groupId.value };
    getText(params);
    // PaginationRef.value.pageInit()
};
const refreshGroup = () => {
    // tableRef.value.reload();
    // ZWGroupRef.value.getGroup();
    // ZWGroupRef.value.changeGroup({ id: groupId.value });
};

const groupIdChange = (groupId_: any) => {
    groupId.value = groupId_;
    defaultParams.groupId = groupId_;
    state.searchParams = { ...deepCopy(defaultParams), group_id: groupId_ };
    tableRef.value.reload();
    ZWGroupRef.value.getGroup();
    ZWGroupRef.value.changeGroup({ id: groupId.value });
};
const searchList = (data: any) => {
    tableRef.value.clearSelect();
    initList(data);
};
onMounted(() => {});
// 选中的内容
watch(table, table => {
    sectionIds.value = getSetionId('id', table.tableData);
});
</script>

<style lang="scss" src="./style.scss" scoped></style>
